import { useDrag, useDrop } from 'react-dnd';
import React, { ReactNode, useRef } from 'react';
import './index.less';
import { UploadFile } from 'antd/es/upload/interface';

const type = 'DragableUploadList';

interface Props {
  originNode: ReactNode;
  moveRow: (drapIndex: number, moveIndex: number) => void;
  file: UploadFile;
  fileList: UploadFile[];
}
export default function DragableUploadListItem(props: Props) {
  const { originNode, moveRow, file, fileList } = props;
  const ref = useRef<HTMLDivElement>(null);
  const index = fileList.indexOf(file);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item) => {
      // @ts-ignore
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    item: { type, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));
  return (
    <div ref={ref} className={`ant-upload-draggable-list-item ${isOver ? dropClassName : ''}`}>
      {originNode}
    </div>
  );
}
